package com.yuji.aacar.core.mvvm.appbase;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.KeyEvent;
import android.widget.Toast;

import com.yuji.aacar.core.cores.event.CoreEventBusMessage;
import com.yuji.aacar.core.cores.event.CoreEventCenter;
import com.yuji.aacar.core.cores.services.CoreServiceResponse;
import com.yuji.aacar.core.cores.utils.LogUtil;
import com.yuji.aacar.core.mvvm.apptask.TaskManager;
import com.yuji.aacar.core.mvvm.apptask.TaskToken;
import com.yuji.aacar.core.mvvm.apptask.ViewModelManager;

import org.greenrobot.eventbus.Subscribe;

import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

/**
 * <li>Package:com.ttp.core.mvvm.appbase</li>
 * <li>Author: lining</li>
 * <li>Date: 2017/2/24</li>
 * <li>Description: FragmentActivity 基类</li>
 */

public abstract class CoreBaseFragmentActivity extends FragmentActivity implements CoreBaseController {

    public String TAG = this.getClass().getSimpleName();

    /**
     * 基类ViewModel对象
     */
    public CoreBaseViewModel coreBaseViewModel;

    /**
     * 请求的viewModelId
     */
    private String viewModelId;

    /**
     * 接收请求params的对象
     */
    public HashMap<String, Object> requestParams;

    public Dialog progressDialog;
    private Toast mToast;

    /**
     * 双击退出应用
     */
    private static Boolean isExit = false;
    private boolean isHome;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent intent = getIntent();
        if (null != intent.getExtras()) {
            viewModelId = intent.getExtras()
                    .getString(AppRoute.ACTIVITY_TOKEN_KEY);
        }
        CoreEventCenter.register(this);
    }

    @Override
    protected void onStart() {
        super.onStart();
        LogUtil.e("--onStart--coreBaseViewModel == null --", coreBaseViewModel == null ? "是空的" : coreBaseViewModel.getClass().getName());
        LogUtil.e("--onStart--coreBaseViewModel == viewModelId --", viewModelId == null ? "没有viewModelId" : viewModelId);
        if (null == coreBaseViewModel) {
            coreBaseViewModel = ViewModelManager.getInstance().viewModelForKey(
                    viewModelId);
            if (null != coreBaseViewModel) {
                LogUtil.e("--onStart--根据viewModelId获得到的coreBaseViewModel--", "[CoreBaseActivity]当前的---coreBaseViewModel---" + coreBaseViewModel.getClass());
                LogUtil.e("--onStart--this--", this.getClass().getSimpleName());
                coreBaseViewModel.setActivity(this);
                alreadyBindBaseViewModel();
                if (coreBaseViewModel.getResponse() != null) {
                    if (coreBaseViewModel.isDataReady.get()
                            && !coreBaseViewModel.isRefreshed.get()) {
                        requestSuccess(coreBaseViewModel.getResponse());
                    } else if (coreBaseViewModel.isFailed.get()) {
                        LogUtil.e("activity", "[" + this.getClass().getSimpleName() + "]" + "[onStart]: coreBaseViewModel.isFailed");
                        coreBaseViewModel
                                .requestFailed(coreBaseViewModel.getResponse());
                    } else {
                        coreBaseViewModel.requestFailed(coreBaseViewModel.getResponse());
                    }
                } else {
                    LogUtil.e("activity", "[" + this.getClass().getSimpleName() + "]" + "[onStart]: coreBaseViewModel.getResponse() == null");
                }
            } else {
                LogUtil.e("activity", this.getClass().getSimpleName() + "[onStart][baseviewmodel]:" + viewModelId + " is null");
                coreBaseViewModel = ViewModelManager.getInstance().newViewModel(this.getClass().getName());
                coreBaseViewModel.showProgressBar = false;
                coreBaseViewModel.setActivity(this);
                viewModelId = coreBaseViewModel.getViewModelId();
                alreadyBindBaseViewModel();
                LogUtil.d("---corebaseactivity---", "create new viewModel:[" + viewModelId + "]");
            }
        } else {
            LogUtil.e("---corebaseactivity---", "[" + this.getClass().getSimpleName() + "]" + "[onStart]: coreBaseViewModel is NOT null (should be null)");
            LogUtil.e("---corebaseactivity---", this.getClass().getSimpleName() + "[onStart][coreBaseViewModel]: is Not Null!");
            LogUtil.e("---corebaseactivity---", this.getClass().getSimpleName() + "[onStart][coreBaseViewModel]:" + coreBaseViewModel.getClass());
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        destoryViewModel();
        CoreEventCenter.unregister(this);
    }

    @Override
    public void onBackPressed() {
        cancelToast();
        super.onBackPressed();
        destoryViewModel();
    }

    /**
     * 双击退出应用
     * @param b 是否是退出页面
     */
    public void setHomePageAndExitApp(boolean b) {
        isHome = b;
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (isHome && (keyCode == KeyEvent.KEYCODE_BACK)) {
            exitBy2Click();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void exitBy2Click() {
        Timer tExit = null;
        if (isExit == false) {
            isExit = true; // 准备退出
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            tExit = new Timer();
            tExit.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false; // 取消退出

                }
            }, 2000); // 如果2秒钟内没有按下返回键，则启动定时器取消掉刚才执行的任务

        } else {
            if (tExit != null) {
                tExit.cancel();
            }
            exit();
        }
    }

    private void exit() {
        finish();
        android.os.Process.killProcess(android.os.Process.myPid());
    }

    public void destoryViewModel() {
        LogUtil.e(this.getClass().getSimpleName(), " destoryViewModel() is called!!!");
        if (coreBaseViewModel != null) {
            LogUtil.e("--destoryViewModel--", coreBaseViewModel);
            TaskManager.getInstance().cancelTask(coreBaseViewModel.getTaskToken());
        }
        ViewModelManager.getInstance().destoryViewModel(viewModelId);
    }

    /*********
     * 网络请求
     * @param method
     */
    public void doTask(String method){
        TaskManager.getInstance().doTask(coreBaseViewModel, method, requestParams);
    }

    /*********
     * 网络请求
     * @param methodName 请求方法名
     * @param params 传入的map
     */
    public void doTask(String methodName, HashMap<String,Object> params){
        TaskManager.getInstance().doTask(coreBaseViewModel, methodName, params);
    }

    /**
     * 取消一个网络请求,需要传入dotask时候返回的唯一令牌
     * @param token 线程对象
     */
    public void cancelTask(TaskToken token) {
        TaskManager.getInstance().cancelTask(token);
    }

    @Subscribe
    public void onEventBusMessage(CoreEventBusMessage message) {
        handleMessage(message);
        if (message.getMessageCode().contentEquals(String.valueOf(CoreEventCenter.BUSSINESS_SERVICE_ERROR))) {
            TaskToken token = new TaskToken();
            token.methodName = message.getMethodName();
            token.requestCode = message.getRequestCode();
            CoreServiceResponse response = new CoreServiceResponse();
            response.setRequestCode(message.getRequestCode());
            response.setTokenObj(token);
            response.setMessage(message.getMessage());
            response.setResultCode(CoreEventCenter.BUSSINESS_SERVICE_ERROR);
            requestFailed(response);
        } else if (message.getMessageCode().contentEquals(String.valueOf(CoreEventCenter.NETWOR_NOT_CONNECT))) {
            TaskToken token = new TaskToken();
            token.methodName = message.getMethodName();
            token.requestCode = message.getRequestCode();
            CoreServiceResponse response = new CoreServiceResponse();
            response.setRequestCode(message.getRequestCode());
            response.setTokenObj(token);
            response.setMessage(message.getMessage());
            response.setResultCode(CoreEventCenter.NETWOR_NOT_CONNECT);
            requestFailed(response);
        }
    }

    public void handleMessage(CoreEventBusMessage message) {

    }
}
